package com.siwei.mes.service.laboratory.factory.material.fly;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.flyAsk.FlyAskAdx;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.fly.DataFlyAdx;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.FlyAshLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 粉煤灰-安定性
 *
 * @Description: 粉煤灰-安定性
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 17:36
 */
@Service
public class FlyAdxFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private FlyAshLaboratoryMapper flyAshLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.FLY_ASK_PARAM_FMH_ADX;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【粉煤灰-{}】", testProjectEnum.getName());
        //将json转成对象
        FlyAskAdx flyAskAdx = objJson.toJavaObject(FlyAskAdx.class);
        if (flyAskAdx == null) {
            log.info("粉煤灰-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        //创建协会粉煤灰安定性对象
        DataFlyAdx dataFlyAdx = new DataFlyAdx();


        dataFlyAdx.setAnDingXingFangFa("雷氏法");

        if (flyAskAdx.getLsf() != null) {
            dataFlyAdx.setPingJunZhi(NullUtils.ifNull(flyAskAdx.getLsf().getPjz()));
            dataFlyAdx.setLeiShiFaJieGuo(NullUtils.ifNull(flyAskAdx.getLsf().getJl()));
            dataFlyAdx.setConclusion(NullUtils.ifNull(flyAskAdx.getLsf().getJl()));
            dataFlyAdx.setZhuQianJuLi1(NullUtils.ifNull(flyAskAdx.getLsf().getJza()));
            dataFlyAdx.setZhuQianJuLi2(NullUtils.ifNull(flyAskAdx.getLsf().getJza1()));
            dataFlyAdx.setZhuHouJiLi1(NullUtils.ifNull(flyAskAdx.getLsf().getJzc()));
            dataFlyAdx.setZhuHouJiLi2(NullUtils.ifNull(flyAskAdx.getLsf().getJzc1()));
            dataFlyAdx.setZhengJiaJuli1(NullUtils.ifNull(flyAskAdx.getLsf().getZjjl()));
            dataFlyAdx.setZhengJiaJuli2(NullUtils.ifNull(flyAskAdx.getLsf().getZjjl1()));


            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_ADX.getCode())) {
                    dataFlyAdx.setBiaoZhunZhi(NullUtils.ifNull(projectInfo.getUnQualifiedCheckOneValue()));
                }
            }

            //设置公共属性
            super.setCommonProperties(sampleNo, experiment, dataFlyAdx, "化学检测室", flyAskAdx.getJcrq(), detail);


            //根据样品编码查询粉煤灰安定性
            DataFlyAdx data_ycl_fmh_adxBySampleNo = flyAshLaboratoryMapper.findDATA_YCL_FMH_ADXBySampleNo(sampleNo);
            //查询没值说明需要  新增粉煤灰安定性
            if (data_ycl_fmh_adxBySampleNo == null) {
                flyAshLaboratoryMapper.addDATA_YCL_FMH_ADX(dataFlyAdx);
            } else {
                //修改粉煤灰安定性值
                flyAshLaboratoryMapper.updateDATA_YCL_FMH_ADX(dataFlyAdx);
            }


            //存储协会需要做的项目集合
            Set<String> set = new HashSet<>();

            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                    if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                        //添加进协会需要做的项目集合
                        set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                    }
                }
            }

            for (String str : set) {
                DataDefaultUc defaultUc = new DataDefaultUc();

                Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

                if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                    log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                    continue;
                }
                String parameterID = itemParameter.get("ParameterID").toString();

                String jcrq = flyAskAdx.getJcrq();
                defaultUc.setConclusion(flyAskAdx.getLsf().getJl());
                defaultUc.setUcResultValue(flyAskAdx.getLsf().getJl());
                defaultUc.setUcTestValue(flyAskAdx.getLsf().getPjz());

                //获取标准值
                for (CheckBatchConfig projectInfo : batchConfigList) {
                    if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_ADX.getCode())) {
                        defaultUc.setUcStandardValue(NullUtils.ifNull(projectInfo.getUnQualifiedCheckOneValue()));
                        defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                    }
                }

                //根据物料信息设置判断配置
                for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                    if (TestProjectEnum.FLY_ASK_PARAM_FMH_ADX.getCode().equals(test.getTestProjectCode())) {
                        if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                            String json = test.getObjJson();
                            super.setUcStandardValue(defaultUc, json, "adx");
                        }
                    }
                }

                //赋值
                super.setDefUc(defaultUc, experiment, "化学检测室", sampleNo, jcrq, detail);

                defaultUc.setUcParameterID(parameterID);//项目id

                //新增或修改DataDefaultUc
                super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
            }
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协会数据到品控：【粉煤灰-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        FlyAskAdx flyAskAdx = objJson.toJavaObject(FlyAskAdx.class);
        if (flyAskAdx == null) {
            log.info("粉煤灰-【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }

        //根据样品编码查询粉煤灰安定性
        DataFlyAdx data = flyAshLaboratoryMapper.findDATA_YCL_FMH_ADXBySampleNo(sampleNo);

        if (data == null) {
            log.info("根据样品编码查询粉煤灰安定性为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }

        FlyAskAdx.Lsf lsf = flyAskAdx.getLsf();
        if (lsf != null) {
            if (data.getPingJunZhi() != null) {
                lsf.setPjz(data.getPingJunZhi());
            }
            if (data.getLeiShiFaJieGuo() != null) {
                lsf.setJl(data.getLeiShiFaJieGuo());
            }
            if (data.getZhuQianJuLi1() != null) {
                lsf.setJza(data.getZhuQianJuLi1());
            }
            if (data.getZhuQianJuLi2() != null) {
                lsf.setJza1(data.getZhuQianJuLi2());
            }
            if (data.getZhuHouJiLi1() != null) {
                lsf.setJzc(data.getZhuHouJiLi1());
            }
            if (data.getZhuHouJiLi2() != null) {
                lsf.setJzc1(data.getZhuHouJiLi2());
            }
            if (data.getZhengJiaJuli1() != null) {
                lsf.setZjjl(data.getZhengJiaJuli1());
            }
            if (data.getZhengJiaJuli2() != null) {
                lsf.setZjjl1(data.getZhengJiaJuli2());
            }
        }
        if (data.getDetectonDate() != null) {
            Date detectonDate = data.getDetectonDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            flyAskAdx.setJcrq(strDate);
        }


        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(flyAskAdx);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.getEquipment()));
        detail.setTemperature(NullUtils.ifNull(data.getTemperature()));
        detail.setHumidness(NullUtils.ifNull(data.getHumidity()));
        detail.setExperimentGist(NullUtils.ifNull(data.getDetectonRuleCode()));
        detail.setJudgeGist(NullUtils.ifNull(data.getAccessRuleCode()));


        if (parameterMap != null && parameterMap.get(detail.getTestProjectCode()) != null) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }

        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
